<template>
  <a-card>
    <!-- 查询区域 -->
    <div :class="{ search: advanced }">
      <a-form layout="horizontal" :labelCol="{ span: 8 }" :wrapperCol="{ span: 15 }">
        <div :class="{ fold: !advanced }">
          <a-row>
            <a-col :md="6" :sm="24">
              <a-form-item label="所属部门">
                <a-tree-select
                  v-model="searchForm.deptId"
                  placeholder="所属部门"
                  :allowClear="true"
                  :dropdown-style="{
                    maxHeight: '400px',
                    overflow: 'auto',
                  }"
                  :tree-data="deptTreeData"
                  :treeDefaultExpandedKeys="[-1]"
                  :replaceFields="{
                    children: 'children',
                    title: 'deptName',
                    key: 'id',
                    value: 'id',
                  }"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="用户编号">
                <a-input
                  v-model="searchForm.userCode"
                  :allowClear="true"
                  placeholder="用户编号"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="登录名">
                <a-input
                  v-model="searchForm.userName"
                  :allowClear="true"
                  placeholder="登录名"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="用户姓名">
                <a-input
                  v-model="searchForm.realName"
                  :allowClear="true"
                  placeholder="用户姓名"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="邮箱">
                <a-input
                  v-model="searchForm.email"
                  :allowClear="true"
                  placeholder="邮箱"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="工作机号">
                <a-input
                  v-model="searchForm.workPhone"
                  :allowClear="true"
                  placeholder="工作机号"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="手机号">
                <a-input
                  v-model="searchForm.mobile"
                  :allowClear="true"
                  placeholder="手机号"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="状态">
                <a-radio-group v-model="searchForm.userStatus" style="width: 100%;">
                  <a-radio :value="-1">禁用</a-radio>
                  <a-radio :value="1">正常</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
          <a-button v-permission="`basic:user:list`" type="primary" @click="handleSearch"
            >查询</a-button
          >
          <a-button class="ml-8" @click="handleReset">重置</a-button>

          <a @click="advanced = !advanced" class="ml-8">
            {{ advanced ? '收起' : '展开' }}
            <a-icon :type="advanced ? 'up' : 'down'" />
          </a>
        </span>
      </a-form>
    </div>

    <!-- 表格区域 -->
    <div>
      <div class="operator">
        <a-button v-permission="`basic:user:add`" class="mr-8" type="primary" @click="handleAddUser"
          >新增</a-button
        >
        <a-button
          v-permission="`basic:user:export`"
          class="mr-8 btn-success"
          type="primary"
          @click="handleExport"
          >数据导出</a-button
        >
        <a-button v-permission="`basic:user:batchDel`" type="danger" @click="handleDelAll"
          >批量删除</a-button
        >
      </div>

      <div style="margin:16px 0;">
        <a-popover
          placement="bottom"
          overlayClassName="columns-select"
          title="列选择"
          :arrowPointAtCenter="true"
          trigger="click"
        >
          <a-icon class="icon-table" type="table" />
          <template slot="content">
            <a-checkbox-group
              class="check-group"
              v-model="colList"
              name="checkboxgroup"
              :options="columnsOptions"
              @change="handleColChange"
            />
          </template>
        </a-popover>
      </div>

      <a-table
        bordered
        :loading="loading"
        :row-key="item => item.id"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :rowSelection="rowSelection"
        @change="handleTableChange"
      >
        <span slot="status" slot-scope="item">
          <a-tag v-if="item === 1" color="green">正常</a-tag>
          <a-tag v-if="item === -1" color="red">禁用</a-tag>
        </span>
        <span slot="action" slot-scope="item">
          <a v-permission="`basic:user:update`" @click="handleEditUser(item)">修改</a>
          <a-divider type="vertical" />
          <a v-permission="`basic:user:del`" class="text-danger" @click="handleDelUser(item)"
            >删除</a
          >
        </span>
      </a-table>
    </div>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form" v-bind="formItemLayout">
        <a-form-item label="所属部门">
          <a-tree-select
            v-decorator="['deptId']"
            placeholder="所属部门"
            :allowClear="true"
            :dropdown-style="{
              maxHeight: '400px',
              overflow: 'auto',
            }"
            :tree-data="deptTreeData"
            :treeDefaultExpandedKeys="[-1]"
            :replaceFields="{
              children: 'children',
              title: 'deptName',
              key: 'id',
              value: 'id',
            }"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="用户姓名">
          <a-input
            v-decorator="['realName', { rules: [{ required: true, message: '请输入用户姓名' }] }]"
            placeholder="请输入用户姓名"
          />
        </a-form-item>
        <a-form-item label="登录名">
          <a-input
            v-decorator="['userName', { rules: [{ required: true, message: '请输入登录名' }] }]"
            placeholder="请输入登录名"
          />
        </a-form-item>
        <a-form-item label="用户编号">
          <a-input
            v-decorator="['userCode', { rules: [{ required: true, message: '请输入用户编号' }] }]"
            placeholder="请输入用户编号"
          />
        </a-form-item>
        <a-form-item label="密码">
          <a-input
            type="password"
            v-decorator="[
              'password',
              {
                rules: [
                  { required: type === 1, message: '请输入密码' },
                  {
                    validator: validateToNextPassword,
                  },
                ],
              },
            ]"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item label="确认密码">
          <a-input
            type="password"
            v-decorator="[
              'confirmPassword',
              {
                rules: [
                  { required: type === 1, message: '请输入确认密码' },
                  {
                    validator: compareToFirstPassword,
                  },
                ],
              },
            ]"
            placeholder="请输入确认密码"
            @blur="handleConfirmPassword"
          />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input v-decorator="['email', { rules: [] }]" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="工作机号">
          <a-input v-decorator="['workPhone', { rules: [] }]" placeholder="请输入工作机号" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-decorator="['mobile', { rules: [] }]" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="角色">
          <a-checkbox-group v-decorator="['roleIdList']" name="roleGroup" :options="roleList" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group
            v-decorator="[
              'userStatus',
              {
                rules: [],
                initialValue: 1,
              },
            ]"
          >
            <a-radio :value="-1">禁用</a-radio>
            <a-radio :value="1">正常</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
// import { saveAs } from 'file-saver';
import moment from 'moment';
import { basicService } from '@/services';
import { transListToTree } from '@/utils/util';
import { SYSTEM } from '@/services/api';

const originColumns = [
  {
    title: '所属部门',
    dataIndex: 'deptName',
    key: 'deptId',
    align: 'center',
    sorter: true,
    ellipsis: true,
    width: 120,
  },
  {
    title: '用户编号',
    dataIndex: 'userCode',
    key: 'userCode',
    align: 'center',
    sorter: true,
    ellipsis: true,
    width: 120,
  },
  {
    title: '登录名',
    key: 'userName',
    dataIndex: 'userName',
    align: 'center',
    sorter: true,
    ellipsis: true,
    width: 120,
  },
  {
    title: '用户姓名',
    key: 'realName',
    dataIndex: 'userName',
    align: 'center',
    sorter: true,
    ellipsis: true,
    width: 120,
  },
  {
    title: '邮箱',
    key: 'email',
    dataIndex: 'email',
    align: 'center',
    sorter: true,
  },
  {
    title: '工作机号',
    key: 'workPhone',
    dataIndex: 'workPhone',
    align: 'center',
    sorter: true,
  },
  {
    title: '手机号',
    key: 'mobile',
    dataIndex: 'mobile',
    align: 'center',
    sorter: true,
  },
  {
    title: '状态',
    key: 'userStatus',
    dataIndex: 'userStatus',
    scopedSlots: { customRender: 'status' },
    align: 'center',
    sorter: true,
    width: 100,
  },
  {
    title: '创建时间',
    key: 'dateCreate',
    dataIndex: 'dateCreate',
    align: 'center',
    customRender: text => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss');
    },
    sorter: true,
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
  },
];

const formItemLayout = {
  labelCol: { span: 6, offset: 2 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'basicUser',

  data() {
    return {
      advanced: true,
      formItemLayout,
      originColumns,
      columns: [],
      columnsOptions: [], // 可选的表格列
      colList: [], // 表格列筛选
      // 搜索表单
      searchForm: {
        deptId: null,
        userCode: null,
        userName: null,
        realName: null,
        email: null,
        workPhone: null,
        mobile: null,
        userStatus: 1,
        sortName: '',
        sortOrder: null,
      },
      dataSource: [],
      pagination: {
        showSizeChanger: true,
        pageSizeOptions: ['10', '50', '100', '200'],
        showQuickJumper: true,
        showTotal: total => `共${total}条`,
        current: 1,
        pageSize: 10,
        total: 0,
      },
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      form: this.$form.createForm(this, { name: 'user-form' }),
      confirmDirty: false,
      confirmLoading: false,
      selectedItem: null,
      deptList: [],
      deptTreeData: [],
      roleList: [], // 所有角色类型
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? '新增' : '修改';
    },
  },

  created() {
    this.getDataSource();
    this.getDeptList();
    this.getRoleList();

    // 初始化表格列
    this.columns = this.originColumns;
    this.columnsOptions = this.originColumns.map(item => {
      return {
        label: item.title,
        value: item.key,
      };
    });
    this.colList = originColumns.map(c => c.key);
  },

  methods: {
    // 查询
    handleSearch() {
      this.getDataSource();
    },

    // 重置
    handleReset() {
      this.searchForm = {
        deptId: null,
        userCode: null,
        userName: null,
        realName: null,
        email: null,
        workPhone: null,
        mobile: null,
        userStatus: 1,
        sortName: '',
        sortOrder: null,
      };
    },

    // 新增
    handleAddUser() {
      this.type = 1;
      this.visible = true;
    },

    // 批量导出
    handleExport() {
      const token = localStorage.getItem('token');
      const url = `${SYSTEM}/user/export?token=${token}`;
      const link = document.createElement('a');
      link.href = url;
      link.click();
    },

    // 批量删除
    handleDelAll() {
      console.log('批量删除', this.rowSelection.selectedRowKeys);
      const that = this;
      const idList = this.rowSelection.selectedRowKeys;

      this.$confirm({
        title: '确认删除吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return new Promise((resolve, reject) => {
            basicService
              .delUserList({ idList })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getDataSource();
                  resolve();
                } else {
                  reject();
                }
              })
              .catch(() => reject());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 表格列筛选
    handleColChange(val) {
      console.log(val);
      this.columns = this.originColumns.filter(col => {
        return val.includes(col.key);
      });
    },

    // 分页切换
    handleTableChange(pagination, filters, sorter) {
      console.log({ pagination, filters, sorter });
      if (sorter.order) {
        this.searchForm.sortName = sorter.columnKey;
        this.searchForm.sortOrder = sorter.order === 'ascend' ? 1 : -1;
      } else {
        this.searchForm.sortName = '';
        this.searchForm.sortOrder = null;
      }
      this.getDataSource();
    },

    // 密码确认
    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (value && value !== form.getFieldValue('password')) {
        callback('两次密码输入不一致！');
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form;
      if (value && this.confirmDirty) {
        form.validateFields(['confirmPassword'], { force: true });
      }
      callback();
    },
    handleConfirmPassword(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },

    // 删除
    handleDelUser(item) {
      console.log(item);
      const that = this;
      this.$confirm({
        title: '确认删除该操作员吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          basicService.delUser({ id }).then(res => {
            console.log(res);
            if (res.code === '200') {
              that.$message.success('操作成功');
              that.getDataSource();
            }
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 修改
    handleEditUser(item) {
      console.log(item);
      const { id } = item;
      basicService.getUserInfo({ id }).then(res => {
        if (res.code === '200') {
          const {
            userCode,
            userName,
            realName,
            email,
            workPhone,
            mobile,
            deptId,
            userStatus,
            roleIdList,
          } = res.data;
          this.$nextTick(() => {
            this.form.setFieldsValue({
              userCode,
              userName,
              realName,
              email,
              workPhone,
              mobile,
              deptId,
              userStatus,
              roleIdList,
            });
          });
        } else {
          this.$message.error(res.msg);
        }
      });

      this.type = 2;
      this.visible = true;
      this.selectedItem = item;
    },

    // 取消新建/修改
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.form.resetFields();
    },

    // 新建/修改确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            basicService
              .addUser(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource();
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            basicService
              .updateUser({ ...values, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.form.resetFields();
                  this.getDataSource();
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 获取数据
    getDataSource() {
      this.loading = true;

      const params = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...this.searchForm,
      };

      // 选择最外层父节点 默认为空
      if (params.deptId === -1) {
        params.deptId = null;
      }

      basicService.getUserList(params).then(res => {
        console.log(res);
        this.dataSource = res.data.content;
        this.pagination.total = res.data.totalElements;
        this.loading = false;
      });
    },

    // 获取部门数据
    getDeptList() {
      basicService.getDeptList({ needDetail: true, canChoose: false }).then(res => {
        if (res.code === '200') {
          this.deptList = res.data.items;
          this.deptTreeData = [
            {
              id: -1,
              deptName: '部门根目录',
              children: transListToTree(res.data.items, -1),
            },
          ];
        }
      });
    },

    // 获取角色数据
    getRoleList() {
      basicService.getAllRole({}).then(res => {
        console.log(res);
        if (res.code === '200') {
          this.roleList = res.data.items.map(item => {
            return {
              label: item.roleName,
              value: item.id,
            };
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>
